﻿using MiniExcelLibs;
using System.Data;
using System.Text.Json;
using TikTokApp.Interfaces;
using TikTokApp.Model;
using TikTokApp.Services;

namespace TikTokApp.Pages
{
    public partial class 用户采集 : UserControl, ITabPage
    {
        public 用户采集()
        {
            InitializeComponent();
            ControlHelper.SetControlHeight(this);
            PerformLayout(); // 强制刷新布局
        }
        private async void InitializeWebView(string keyword)
        {
            await webView21.EnsureCoreWebView2Async(null);
            string searchUrl = $"https://www.douyin.com/search/{Uri.EscapeDataString(keyword)}?type=user";

            // Navigate to the URL
            webView21.CoreWebView2.Navigate(searchUrl);

            // 等待页面加载完成
            webView21.CoreWebView2.NavigationCompleted += async (s, e) =>
            {
                // Delay for 1 second, then close the message box
                await Task.Delay(1000); // 1 second delay
                await ScrollAndExtract();
            };
        }

        async Task<bool> IsEndOfPageAsync()
        {
            // 暂时没有更多了
            var result = await webView21.CoreWebView2.ExecuteScriptAsync(@"
                (function() {
                    let endElement = document.querySelector('.shrAJJLa'); 
                    if (endElement) {
                        return true;
                    }
                    return false;
                })();
            ");
            return bool.Parse(result);
        }

        int currentCount = 0;
        bool isScrolling = true;

        public event EventHandler CloseRequested;

        public string PageTitle => "数据采集";

        public bool AllowClose => true;

        // 自动滚动并提取达人信息
        private async Task ScrollAndExtract()
        {
            // Start the loop for scrolling
            while (isScrolling)
            {
                // 检查是否出现 "暂时没有更多了"
                if (await IsEndOfPageAsync())
                {
                    isScrolling = false;
                    AddlistBox1Msg("已滚动到底部，停止采集,正在导出数据");
                    Btn_export_Click(btn_export, EventArgs.Empty); // 直接调用事件方法
                    break;
                }
                // Execute the script to get the current item count
                var countStr = await webView21.CoreWebView2.ExecuteScriptAsync(@"
                    var itemCount = document.querySelectorAll('ul[data-e2e=""scroll-list""] li').length;
                    itemCount;
                ");

                // Convert result to integer
                currentCount = int.Parse(countStr);
                AddlistBox1Msg($"{DateTime.Now}采集到达人数据{currentCount},继续采集中...");

                // Perform scrolling
                await webView21.CoreWebView2.ExecuteScriptAsync("window.scrollBy(0, 1000);");
                await Task.Delay(new Random().Next(1000, 6000)); // Random delay between scrolls
            }
        }

        // 创建 Excel 文件并保存
        public void ExportToExcel(List<DouyinUser> users, string sheetName)
        {
            if (users == null || users.Count == 0)
            {
                AddlistBox1Msg($"无可导出的达人数据");
                return;
            }

            string timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");
            string fileName = $"{sheetName}_{timestamp}.xlsx";
            string filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), fileName);

            var data = users.Select(u => new Dictionary<string, object>
            {
                { "名称", u.name },
                { "抖音号", u.douyinid },
                { "获赞数", u.likes },
                { "粉丝数", u.followers },
                { "简介", u.bio },
                { "主页链接", u.profileurl }
            }).ToList();

            using (var stream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
            {
                MiniExcel.SaveAs(stream, data);
            }
            AddlistBox1Msg($"采集完成，共{users.Count}个达人信息。\n导出文件路径: {filePath}");
        }

        private void SearchButton_Click(object sender, EventArgs e)
        {
            // Get the keyword from the TextBox
            string keyword = searchTextBox.Text.Trim();
            if (string.IsNullOrEmpty(keyword))
            {
                MessageBox.Show("Please enter a keyword.");
                return;
            }

            this.listBox1.Visible = true;
            this.listBox1.Items.Clear();
            this.isScrolling = true;
            InitializeWebView(keyword);
        }

        private async void Btn_export_Click(object sender, EventArgs e)
        {
            // 执行 JavaScript 提取达人信息
            string script = @"
                (function() {
                    let results = [];
                    document.querySelectorAll('ul[data-e2e=""scroll-list""] li').forEach(item => {
                        let user = {
                            name: item.querySelector('p.v9LWb7QE')?.innerText.trim() || '',
                            douyinid: item.querySelector('div.jjebLXt0 span:nth-child(1) span')?.innerText.trim() || '',
                            likes: item.querySelector('div.jjebLXt0 span:nth-child(3)')?.innerText.replace('获赞', '').trim() || '',
                            followers: item.querySelector('div.jjebLXt0 span:nth-child(5)')?.innerText.replace('粉丝', '').trim() || '',
                            bio: item.querySelector('p.Kdb5Km3i')?.innerText.trim() || '',
                            profileurl: item.querySelector('a[class*=""WHgA""]') ? 'https:' + item.querySelector('a[class*=""WHgA""]').getAttribute('href') : ''
                        };
                        results.push(user);
                    });
                    return results;
                })();
            ";

            var result = await webView21.CoreWebView2.ExecuteScriptAsync(script);
            if (!string.IsNullOrWhiteSpace(result))
            {
                List<DouyinUser> users = JsonSerializer.Deserialize<List<DouyinUser>>(result);
                ExportToExcel(users, searchTextBox.Text.Trim());
                AddlistBox1Msg($"采集完成，共{users.Count}个达人信息。文件已导出在桌面");
            }
        }

        private void Btn_StopScroll_Click(object sender, EventArgs e)
        {
            this.isScrolling = false;
        }

        public void AddlistBox1Msg(string message)
        {
            // 添加新数据
            listBox1.Items.Add(message);
            // 确保最多只保留5条数据
            while (listBox1.Items.Count > 10)
            {
                listBox1.Items.RemoveAt(0); // 移除最早的一条
            }
        }

        public UserControl AsUserControl() => this;

        public void OnPageActivated()
        {
            // 激活时恢复采集状态
        }

        public void OnPageDeactivated()
        {

        }
    }
}
